package com.cssl.gulimall.cart.web;

import com.cssl.common.vo.cart.CartItemVO;
import com.cssl.common.vo.cart.CartVO;
import com.cssl.gulimall.cart.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.concurrent.ExecutionException;

@Controller
public class CartController {
    @Autowired
    private CartService cartService;

    /**
     * 添加商品到购物车
     */
    @GetMapping("/addCartItem")
    public String addCartItem(@RequestParam("skuId")Long skuId, @RequestParam("num") Integer num,
                              RedirectAttributes attributes) throws ExecutionException, InterruptedException {
        //添加sku商品到购物车
        cartService.addToCart(skuId,num);
        attributes.addAttribute("skuId",skuId);
        return  "redirect:http://cart.gulimall.com/addToCartSuccessPage.html";
    }

    /**
     * 商品添加到购物车成功页(防刷)
     */
    @GetMapping(value = "/addToCartSuccessPage.html")
    public String addToCartSuccessPage(@RequestParam("skuId") Long skuId, Model model){
        //重定向到成功页面，再次查询购物车数据即可
        CartItemVO cartItemVO = cartService.getCartItem(skuId);
        model.addAttribute("item",cartItemVO);
        return "success";
    }

    @GetMapping("/cart.html")
    public String cartListPage(Model model) throws ExecutionException, InterruptedException {
        CartVO cartVO = cartService.getCart();
        model.addAttribute("cart",cartVO);
        return "cartList";
    }

    @GetMapping("/deleteItem")
    public String deleteItem(@RequestParam("skuId")Integer skuId){
        cartService.deleteIdCartInfo(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    /**
     * 改变商品数量
     */
    @GetMapping("/countItem")
    public String countItem(@RequestParam("skuId") Long skuId,@RequestParam("num")Integer num){
        cartService.changeItemCount(skuId,num);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    /**
     * 更改购物车商品选择状态
     */
    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId")Long skuId,@RequestParam("checked")Integer check){
        cartService.checkItem(skuId,check);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
}
